import sys
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtCore import QThread, pyqtSignal, QObject
from time import sleep
import threading
from PyQt5.QtNetwork import QUdpSocket, QHostAddress

class UDP_Qthread_function(QObject):
    
    signal_UDP_qthread_function_Init = pyqtSignal()
    signal_pushButton_Open           = pyqtSignal(object)
    signal_pushButton_Open_flag      = pyqtSignal(object)
    signal_readyRead                 = pyqtSignal(object)
    signal_send_data                 = pyqtSignal(object)
    signal_send_data_num             = pyqtSignal(object)
    signal_udp_max_bandwidth_test    = pyqtSignal(object)
    
    def __init__(self, parent=None):
        super(UDP_Qthread_function, self).__init__(parent)
        #开始调用网络信号
        self.state = 0 #0 未打开 1 打开 2 关闭

    def slot_pushButton_Open(self,parameter):
        print("打开UDP", parameter)
        if self.state == 0:
            if self.udpsocket.bind(QHostAddress(parameter['ip']), int(parameter['port'])):
                self.state = 1
                self.signal_pushButton_Open_flag.emit(1)
            else:
                self.signal_pushButton_Open_flag.emit(0)
        else:
            self.udpsocket.close()
            self.state = 0
            self.signal_pushButton_Open_flag.emit(2)
        
    def slot_readyRead(self):
        buf = bytes()
        buf,ip,port = self.udpsocket.readDatagram(1024)
        data = {}
        data['ip']   = ip.toString()
        data['port'] = port
        data['buf']  = buf
        self.signal_readyRead.emit(data)
        # print("UDP收到数据", ip.toString(), port, buf)
        
    def slot_send_data(self,parameter):
        print("UDP 发送数据", parameter)
        if self.state != 1:
            return
        ip_port = parameter['ip_port'].split(':',1)
        ip = ip_port[0]
        port = int(ip_port[1])
        print("UDP发送数据", ip_port)
        self.udpsocket.writeDatagram(parameter['data'], QHostAddress(ip), int(port))
        self.signal_send_data_num.emit(len(parameter['data']))
        
    def UDP_qthread_function_Init(self):
        self.udpsocket = QUdpSocket()
        self.udpsocket.readyRead.connect(self.slot_readyRead)